package com.jiuli_travel.blog_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuli_travel.blog_service.mapper.BlogCommentMapper;
import com.jiuli_travel.blog_service.model.cache.blog_comment.BlogCommentLiked;
import com.jiuli_travel.blog_service.model.dto.blog_comment.BlogCommentInsertRequest;
import com.jiuli_travel.blog_service.model.dto.blog_comment.BlogCommentQueryRequest;
import com.jiuli_travel.blog_service.model.entity.BlogComment;
import com.jiuli_travel.blog_service.model.vo.BlogCommentVO;
import com.jiuli_travel.blog_service.service.IBlogCommentService;
import com.jiuli_travel.user_service.model.cache.UserCache;
import com.jiuli_travel.user_service.model.vo.UserVO;
import com.jiuli_travel.user_service.service.IUserService;
import com.jiuli_travel.utils.PageDTO;
import com.jiuli_travel.utils.Result;
import com.jiuli_travel.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment> implements IBlogCommentService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private BlogCommentLiked blogCommentLiked;

    @Autowired
    private IUserService userService;


    /**
     * 分页获取某个博客的评论信息（底层的回复也是分页查询）初始化形式
     */
    @Override
    public PageDTO<BlogCommentVO> selectInitBlogCommentsByPage(Long blogId){
        /**
         * 获取一级评论的信息
         */
        BlogCommentQueryRequest blogCommentQueryRequest = new BlogCommentQueryRequest();
        blogCommentQueryRequest.setBlogId(blogId);
        blogCommentQueryRequest.setParentId(0L);
        PageDTO<BlogCommentVO> blogCommentVOPageDTO = selectCommentsByPage(blogCommentQueryRequest);
        if (blogCommentVOPageDTO == null){
            return null;
        }

        /**
         * 获取 son 评论信息 （一条即可）
         */
        blogCommentQueryRequest.setPage(1);
        blogCommentQueryRequest.setSize(1);

        blogCommentVOPageDTO.getRecords()
                        .forEach(blogCommentVO -> {
                            /**
                             * 获取， 封装
                             */
                            blogCommentQueryRequest.setParentId(blogCommentVO.getId());
                            PageDTO<BlogCommentVO> sonBlogCommentVOPageDTO = selectCommentsByPage(blogCommentQueryRequest);
                            blogCommentVO.setSonBlogCommentVOList(sonBlogCommentVOPageDTO);
                        });

        return blogCommentVOPageDTO;

    }

    /**
     * 获取评论信息
     */
    @Override
    public PageDTO<BlogCommentVO> selectCommentsByPage(BlogCommentQueryRequest blogCommentQueryRequest){
        //获取用户的id
        Long userId = UserHolder.getUser().getId();
        /**
         * 对评论信息的操作
         */
        //构造分页排序条件
        Page<BlogComment> mp = blogCommentQueryRequest.toMp();

        //构造查询条件并查询 TODO 分页条件查询要在条件中查 （坑批）
        lambdaQuery()
                .eq(blogCommentQueryRequest.getBlogId() != null, BlogComment::getBlogId, blogCommentQueryRequest.getBlogId())
                .eq(BlogComment::getParentId, blogCommentQueryRequest.getParentId()).page(mp);

        //校验上是否有评论数据
        if(mp.getTotal() == 0){
            return null;
        }

        //转化数据格式
        PageDTO<BlogCommentVO> blogCommentVOPageDTO = PageDTO.of(mp, BlogComment.class, BlogCommentVO.class);

        /**
         * TODO 获取该评论者 | 被评论者的基础信息
         */
        blogCommentVOPageDTO.getRecords()
                .forEach(blogCommentVO -> {
                    /**
                     * 1. TODO 获取评论者的信息
                     */
                    //1.1 发起请求获取数据
                    UserVO userVO = getUserByUserId(blogCommentVO.getUserId());
                    //1.2 封装用户信息
                    blogCommentVO.setUserVO(userVO);

                    /**
                     * 2. TODO 获取被评论者的信息 （评论者是一级id, 或者被评论者的是一级评论则不用）
                     * TODO 后面再完整处理
                     */
                    if(blogCommentVO.getAnswerId() == 0){
                        return;
                    }
                    //1.1 发起请求获取数据
                    String userName = getUserByUserId(blogCommentVO.getAnswerId()).getUserName();
                    //1.2 封装用户信息
                    blogCommentVO.setAnswerUserName(userName);

                    /**
                     * 3. TODO 对该评论进行分析，获取该评论对于当前登录用户是否有点赞
                     */
                    boolean flag = blogCommentLiked.isLikedBlogComment(userId, blogCommentVO.getId());
                    blogCommentVO.setLikedFlag(flag);

                });
        return blogCommentVOPageDTO;
    }

    //发表个人博客评论
    @Override
    public void publishBlogComment(BlogCommentInsertRequest blogCommentInsertRequest) {
        //获取发表该评论的用户信息
        Long userId = UserHolder.getUser().getId();
        //添加评论信息
        BlogComment blogComment = new BlogComment();
        blogComment = BeanUtil.copyProperties(blogCommentInsertRequest, BlogComment.class);
        blogComment.setUserId(userId);
        //创建
        save(blogComment);
    }

    //删除个人博客评论
    @Override
    public void delBlogComment(Long blogCommentId) {
        //TODO 一级评论信息需要管理员进行删除
        /**
         * 判断是不是一级评论信息 TODO 制定规则
         */
        //构造删除条件
        LambdaQueryChainWrapper<BlogComment> removeWrapper = lambdaQuery()
                .eq(BlogComment::getId, blogCommentId)
                .ne(BlogComment::getParentId, 0);

        //删除
        boolean remove = remove(removeWrapper);
    }

    /**
     * 获取用户的信息
     */
    private UserVO getUserByUserId(Long userId) {
//        String url = "http://localhost:8083/user/getUserByUserId?"+"userId="+ userId;
//        Result result = restTemplate.getForObject(
//                url,
//                Result.class
//        );
        Result result = userService.getUserByUserId(userId);
        assert result != null;
        return BeanUtil.toBean(result.getData(), UserVO.class);
    }

}